package com.zhengke.common.util;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.Resources;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * *******************************
 * 项目名称：tvmall-parent
 * 文件名称：FastDfsApiOpr
 * 类说明：  FastDfs工具类
 * 创建时间：2020/2/11 14:14
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
public class FastDfsApiOpr {
    //加载配置文件
    //public static String CONF_FILENAME = FastDfsApiOpr.class.getResource("/fdfs_client.conf");

    //public static String CONF_FILENAME = "G:/java-project/java-parent/tvmallbs Maven Webapp/src/main/resources/fdfs_client.conf";
    public static String CONF_FILENAME = CommonUtil.getClassesPath() + "fdfs_client.conf";

    /**
     * 上传文件
     *
     * @param file
     * @param extName
     * @return
     */
    public static String upload(byte[] file, String extName) {

        try {
            // 1、把FastDFS提供的jar包添加到工程中
            // 2、初始化全局配置。加载一个配置文件
            ClientGlobal.init(CONF_FILENAME);
            // 3、创建一个TrackerClient对象。
            TrackerClient tracker = new TrackerClient();
            // 4、创建一个TrackerServer对象。通过管理客户端构建
            TrackerServer trackerServer = tracker.getConnection();
            // 5、声明一个StorageServer对象，null。
            StorageServer storageServer = null;
            // 6、获得StorageClient对象。通过管理服务端和存储服务端构建
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
           /* NameValuePair nvp[] = new NameValuePair[]{
                    new NameValuePair("age", "18"),
                    new NameValuePair("sex", "male")
            };*/
            // 7、直接调用StorageClient对象方法上传文件即可。
            //参数 文件绝对路径  文件上传后的扩展名png  文件的扩展信息
            //eg: "E:\\user\\Pictures\\one.png","png",null
            String fileIds[] = storageClient.upload_file(file, extName, null);

            System.out.println(fileIds.length);
            System.out.println("组名：" + fileIds[0]);
            System.out.println("路径: " + fileIds[1]);
            return "/" + fileIds[0] + "/" + fileIds[1];

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件
     *
     * @param filePath
     * @param extName
     * @return
     */
    public static String upload(String filePath, String extName) {

        try {
            // 1、把FastDFS提供的jar包添加到工程中
            // 2、初始化全局配置。加载一个配置文件
            ClientGlobal.init(CONF_FILENAME);
            // 3、创建一个TrackerClient对象。
            TrackerClient tracker = new TrackerClient();
            // 4、创建一个TrackerServer对象。通过管理客户端构建
            TrackerServer trackerServer = tracker.getConnection();
            // 5、声明一个StorageServer对象，null。
            StorageServer storageServer = null;
            // 6、获得StorageClient对象。通过管理服务端和存储服务端构建
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            //这个参数可以指定，也可以不指定，如果指定了，可以根据 testGetFileMate()方法来获取到这里面的值
           /* NameValuePair nvp[] = new NameValuePair[]{
                    new NameValuePair("age", "18"),
                    new NameValuePair("sex", "male")
            };*/
            // 7、直接调用StorageClient对象方法上传文件即可。
            //参数 文件绝对路径  文件上传后的扩展名png  文件的扩展信息
            //eg: "E:\\user\\Pictures\\one.png","png",null
            String fileIds[] = storageClient.upload_file(filePath, extName, null);

            System.out.println(fileIds.length);
            System.out.println("组名：" + fileIds[0]);
            System.out.println("路径: " + fileIds[1]);
            return "/" + fileIds[0] + "/" + fileIds[1];
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载文件
     *
     * @param groupName
     * @param fileName
     * @return
     */
    public static byte[] download(String groupName, String fileName) {
        try {

            ClientGlobal.init(CONF_FILENAME);

            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            byte[] b = storageClient.download_file(groupName, fileName);
            return b;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    @Test
//    public void testGetFileInfo(){
//        try {
//            ClientGlobal.init(conf_filename);
//
//            TrackerClient tracker = new TrackerClient();
//            TrackerServer trackerServer = tracker.getConnection();
//            StorageServer storageServer = null;
//
//            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
//            FileInfo fi = storageClient.get_file_info("group1", "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf");
//            System.out.println(fi.getSourceIpAddr());
//            System.out.println(fi.getFileSize());
//            System.out.println(fi.getCreateTimestamp());
//            System.out.println(fi.getCrc32());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    @Test
//    public void testGetFileMate(){
//        try {
//            ClientGlobal.init(conf_filename);
//
//            TrackerClient tracker = new TrackerClient();
//            TrackerServer trackerServer = tracker.getConnection();
//            StorageServer storageServer = null;
//
//            StorageClient storageClient = new StorageClient(trackerServer,
//                    storageServer);
//            NameValuePair nvps [] = storageClient.get_metadata("group1", "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf");
//            for(NameValuePair nvp : nvps){
//                System.out.println(nvp.getName() + ":" + nvp.getValue());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 删除文件
     *
     * @param groupName
     * @param fileName
     */
    public static void delete(String groupName, String fileName) {

        try {
            ClientGlobal.init(CONF_FILENAME);

            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer,
                    storageServer);
            int i = storageClient.delete_file(groupName, fileName);
            System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除异常," + e.getMessage());
        }
    }


    /**
     * 删除文件
     *
     * @param fileId
     */
    public static void deleteFile(String fileId) {
        /**
         * 删除已经之前上传到服务器的图片，节省存储资源
         */
        //先判断fdfs图片服务器上原图片是否存在
        boolean isExist = false;

        try {
            String urlStr = LoadProperties.findValue("FILE_SERVER_URL") + fileId;
            URL url = new URL(urlStr);// 注：urlStr中需将空格替换为%20,否则报505
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int state = conn.getResponseCode();
            if (state == 200) {
                isExist = true;
            } else {
                isExist = false;
            }

            //排除修改为fdfs上传之前路径问题
            int index = fileId.indexOf("/");
            if (fileId != null && index >= 0 && isExist == true) {
                // eg:    /group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                fileId = fileId.substring(1);//   group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                String groupName = fileId.substring(0, fileId.indexOf("/"));//group01
                String fileName = fileId.substring(fileId.indexOf("/") + 1);///M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg

                ClientGlobal.init(CONF_FILENAME);

                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;

                StorageClient storageClient = new StorageClient(trackerServer,
                        storageServer);
                int i = storageClient.delete_file(groupName, fileName);
                System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除异常," + e.getMessage());
        }

    }
}